class Admin::ClientsController < ApplicationController
  layout 'admin'

  before_filter :authenticate_user!, :check_if_admin

  def index
    @clients = Client.active.paginate(:page => params[:page], :per_page => 50).order('name ASC')

    respond_to do |format|
      format.html
    end
  end

  def show
    @client = Client.find(params[:id])

    respond_to do |format|
      format.html
    end
  end

  def new
    @client = Client.new
    @user = @client.build_user
  end

  def create
    @user = User.new(params[:user])
    @client = Client.new(params[:client])

    respond_to do |format|
      begin
        if @user.valid?
          if @client.valid?
            # Saves the user only if both the user and client are valid.
            @user.save

            # Assigns the reference for the user to the client.
            @client.user_id = @user.id

            # Saves the client.
            @client.save

            @user.assign_role("Client")
            format.html { redirect_to admin_clients_url }
          else
            # Render view with errors.
            format.html { render :new }
          end
        else
          # Render view with errors.
          format.html { render :new }
        end
      rescue
        # Render view with errors.
        format.html { render :new }
      end
    end
  end

  def edit
    @client = Client.find(params[:id])
    @user = @client.user

    respond_to do |format|
      format.html
    end
  end

  def update
    @client = Client.find(params[:id])

    respond_to do |format|
      if @client.update_attributes(params[:client])
        flash[:notice] = "El cliente ha sido actualizado."
        format.html { redirect_to admin_clients_url }
      else
        # Render view with errors.
        format.html { render :new }
      end
    end
  end

  def destroy
    @client = Client.find(params[:id])

    if @client.destroy_client
      flash[:success] = 'El cliente ha sido eliminado.'
    else
      flash[:fail] = 'El cliente no ha podido ser eliminado. Intente nuevamente.'
    end

    respond_to do |format|
      format.html { redirect_to admin_clients_url }
    end
  end

  def search
    keywords = params[:keywords]

    @clients = Client.unscoped.search(keywords).paginate(:page => params[:page], :per_page => 50)

    respond_to do |format|
      format.html
    end
  end

end
